﻿using System.Collections.Generic;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell.Interop;

namespace TellagoInc.VsTagExplorer.TagSelector
{
    public class AddTagsWorker : TagsWorker
    {
        public AddTagsWorker(DTE envDte, SVsSolution solution, TagsSelector selector) : base(envDte, solution, selector)
        {
        }

        protected override void ApplyTags(string currentTags, string newTags,
                                          IVsBuildPropertyStorage buildPropertyStorage, uint itemId)
        {
            //Make sure we are not appending already existing ones.
            currentTags = currentTags ?? string.Empty;
            newTags = newTags ?? string.Empty;
            
            IEnumerable<string> oldTags =
                currentTags.Split(' ').Select(t => t.Trim()).Where(t => !string.IsNullOrWhiteSpace(t));
            IEnumerable<string> addingTags =
                newTags.Split(' ').Select(t => t.Trim()).Where(
                    t => !string.IsNullOrWhiteSpace(t) && !oldTags.Any(o => o == t));

            buildPropertyStorage.SetItemAttribute(itemId, "Tags",
                                                  string.Join(" ", oldTags) + " " + string.Join(" ", addingTags));
        }
    }
}